package com.shujia.letter.sub;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/*
让存钱和取钱交替执行
 */
public class Account {
    private String no;

    private int balance;

    private int money;

    // true 表示有钱, false 表示账号没钱
    private boolean flag = false;

    private Lock lock = new ReentrantLock();

    private Condition condition = lock.newCondition();


    // 存钱
    public void depsit(int money) {
        /*
        考虑账户是否有钱, 如果账号没钱的话可以存钱
        账号有钱, 等待其他线程取钱之后才能存钱
         */
        try {
            lock.lock();
            while (flag) {
                condition.await();
            }
            // 执行存钱的逻辑
            System.out.println(Thread.currentThread().getName() + "存钱:" + money);
            balance += money;

            // 账号有钱了
            flag = true;

            condition.signalAll();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }


    }

    // 取钱
    public void draw(int money) {
        try {
            lock.lock();
            // 没钱的时候, 进入等待队列
            while (!flag) {// 条件判断的时候一定要使用while, 不要用if
                condition.await();
            }

            System.out.println(Thread.currentThread().getName() + "取钱:" + money);
            balance -= money;

            // 取钱后, 代表没钱了
            flag = false;

            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }


    }


}
